package com.ittx.dzt.tiktok.service;

import cn.hutool.core.collection.CollectionUtil;
import com.ittx.dzt.business.constant.StoreExtendConstant;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.TimeFrameDTO;
import com.ittx.dzt.sys.response.Result;
import com.ittx.dzt.sys.util.json.JacksonTool;
import com.ittx.dzt.tiktok.constant.TiktokApiConstant;
import com.ittx.dzt.tiktok.handler.AbstractTiktokByTimeApiHandler;
import com.ittx.dzt.tiktok.util.TiktokUtil;
import lombok.extern.slf4j.Slf4j;
import open.constant.PlatformApiConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 全球商品增量下载
 * <p>
 * cy.sku.onSale.download
 * /product/202312/global_products/search（全球商品查询）
 * https://partner.tiktokshop.com/docv2/page/65854fa5a46cdd02bcbd0a18?external_id=65854fa5a46cdd02bcbd0a18
 * </p>
 *
 * @author gywang
 * @since 2024-07-13
 */
@Slf4j
@Service
public class TiktokGlobalSkuDownloadByTimeframeService extends AbstractTiktokByTimeApiHandler<TimeFrameDTO> {

	private static final int DEFAULT_PAGE_SIZE = 100;
	@Autowired
	private TiktokSkuDownloadBySpuIdService tiktokSkuDownloadBySpuIdService;


	@Override
	protected String getMqTopic() {
		return TiktokApiConstant.Rocket.TIKTOK_PRODUCT_LIST_BY_TIME_BATCH_SPLIT_TOPIC;
	}

	@Override
	public String getTiktokMethod() {
		return TiktokApiConstant.GLOBAL_PRODUCT_LIST_BY_TIME;
	}

	@Override
	public String getLocalApiMethod() {
		return PlatformApiConstant.InboundInterface.SKU_DOWNLOAD_BY_TIMEFRAME;
	}

	@Override
	protected Result<?> doProcessByNormalType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		Map<String, Boolean> logMap = new HashMap<>();
		return this.requestList(platformApiParamDTO, timeFrameDTO, logMap);
	}

	@Override
	protected Result<?> doProcessByCheckType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		return this.requestList(platformApiParamDTO, timeFrameDTO, null);
	}

	@Override
	protected Result<?> doProcessByIdType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		return this.asyncHandlerById(platformApiParamDTO, platformApiParamDTO.getPlatformIdentifierTag());
	}

	/**
	 * 请求平台接口
	 */
	private Result<?> requestList(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO, Map<String, Boolean> logMap) {
		Map<String, Object> params = new HashMap<>();
		// api文档中，并没有说要shop_cipher
		// String shop_cipher = (String) TiktokUtil.getExtendValue(platformApiParamDTO.getStoreConfig().getExtendMap(), StoreExtendConstant.TIKTOK_STORE_CIPHER);
		// 店铺密码
		params.put("shop_cipher", getShopCipher(platformApiParamDTO));
		// 每页查询数量
		params.put("page_size", DEFAULT_PAGE_SIZE);
		Map<String, Object> reqBody = new HashMap<>();
		// 开始时间
		reqBody.put("update_time_ge", timeFrameDTO.getFrom().toEpochSecond(ZoneOffset.of("+8")));
		// 结束时间
		reqBody.put("update_time_le", timeFrameDTO.getTo().toEpochSecond(ZoneOffset.of("+8")));
		String body = JacksonTool.toJson(reqBody);
		Result<?> result = this.executeTiktokApi(getDefaultUrl(platformApiParamDTO.getStoreConfig()), platformApiParamDTO.getStoreConfig(), params, null, platformApiParamDTO.getRequestId(), TiktokApiConstant.ApiHttpMethod.POST);
		if (!result.isSuccess()) {
			return result;
		}
		Map<String, Object> resultMap = (Map<String, Object>) result.getData();
		Map<String, Object> dataMap = (Map<String, Object>) resultMap.get(DATA_FIELD);
		// 商品总数
		Integer total = Integer.parseInt(dataMap.get(RESULT_TOTAL).toString());
		// 探查模式只返回商品总数
		if (PlatformApiConstant.ApiByTime.CHECK.equals(platformApiParamDTO.getQueryType())) {
			return Result.success().addData(total);
		}
		List<Map<String, Object>> items = (List<Map<String, Object>>) dataMap.get("global_products");
		if (CollectionUtil.isNotEmpty(items)) {
			// 分发数据到MQ，异步消费下载
			for (Map<String, Object> item : items) {
				String productId = item.get("id") + "";
				sendToSplitTopic(platformApiParamDTO, productId, logMap);
			}
		}
		String nextToken = dataMap.get("next_page_token").toString();
		while (StringUtils.isNotBlank(nextToken)) {
			params.put("page_token", nextToken);
			result = this.executeTiktokApi(getDefaultUrl(platformApiParamDTO.getStoreConfig()), platformApiParamDTO.getStoreConfig(), params, body, platformApiParamDTO.getRequestId(), TiktokApiConstant.ApiHttpMethod.POST);
			if (!result.isSuccess()) {
				return result;
			}
			resultMap = (Map<String, Object>) result.getData();
			dataMap = (Map<String, Object>) resultMap.get(DATA_FIELD);
			nextToken = (String) dataMap.get("next_page_token");
			items = (List<Map<String, Object>>) dataMap.get("global_products");
			if (CollectionUtil.isNotEmpty(items)) {
				// 分发数据到MQ，异步消费下载
				for (Map<String, Object> item : items) {
					String productId = item.get("id") + "";
					sendToSplitTopic(platformApiParamDTO, productId, logMap);
				}
			}
		}
		return Result.success().addData(logMap);
	}

	/**
	 * 多线程处理逻辑
	 */
	@Override
	public Result<?> asyncHandlerById(PlatformApiParamDTO platformApiParamDTO, String productId) {
		Result<?> result = tiktokSkuDownloadBySpuIdService.getProductBySdk(productId, platformApiParamDTO);
		if (!result.isSuccess()) {
			return result;
		}
		return this.sendRequestToPlatform(platformApiParamDTO, result.getData(), true);
	}
}
